package com.hdculture.simple.expensemanager.premium;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;

import com.hdculture.simple.expensemanager.premium.R;

import android.app.Activity;
import android.app.Dialog;
import android.widget.*;
import android.widget.AdapterView.OnItemClickListener;
import android.util.Log;
import android.view.*;
import android.os.Bundle;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;

public class ItemDetailActivity extends Activity {
	//private CoreDBAdapter dbHelper;
	ListView expenseList;
	CoreDBAdapter dbAdapter;
	Button backButton, addExpenseButton, actionsButton;
	EditText rowIDText;
	String item="";
	String currencySign="$";
	TextView itemText;
	String tag = "ItemDetailActivity";
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
    	dbAdapter.close();
    	Log.i(tag,"DB Connection Closed");
		super.onPause();
	}
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		dbAdapter.open();
		Log.i(tag,"DB Connection Resume");
		super.onResume();
	}
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.itemdetail);
//        dbHelper = new CoreDBAdapter(IncomeSourceDetailActivity.this);
//        dbHelper.open();
        
        expenseList = (ListView)findViewById(R.id.expenseList);
        Intent i = getIntent();
        Bundle b = i.getExtras();
        item=b.getString("ITEM");
        itemText = (TextView)findViewById(R.id.itemText);
        itemText.setText(item);
        dbAdapter= new CoreDBAdapter(this);
        dbAdapter.open();
        Log.i(tag,"DB Connection Open");
        currencySign = dbAdapter.getCurrencySign();
        buildList();
        rowIDText = (EditText)findViewById(R.id.rowIDText);
        actionsButton = (Button)findViewById(R.id.actionsButton);
        backButton = (Button)findViewById(R.id.backButton);
        backButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				finish();
			}
		});
        addExpenseButton = (Button)findViewById(R.id.addExpenseButton);
        addExpenseButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				final Dialog incomeInputDialog = new Dialog(ItemDetailActivity.this);
				incomeInputDialog.setTitle("Add Income");
				incomeInputDialog.setContentView(R.layout.addexpensedialog);
				final Button closeButton = (Button)incomeInputDialog.findViewById(R.id.cancelButton);
				final Button addIncomeButton = (Button)incomeInputDialog.findViewById(R.id.addButton);
				final EditText itemDescriptionText = (EditText)incomeInputDialog.findViewById(R.id.itemDescriptionText);
				itemDescriptionText.setText(itemText.getText().toString());
				itemDescriptionText.setEnabled(false);
				itemDescriptionText.setFocusable(false);
				
				final EditText itemPriceText = (EditText)incomeInputDialog.findViewById(R.id.itemPriceText);
				closeButton.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View arg0) {
						incomeInputDialog.dismiss();
					}
				});
				addIncomeButton.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View arg0) {
						//Getting the values and saving it to the database...
						dbAdapter.addExpense(itemText.getText().toString(), Double.parseDouble(itemPriceText.getText().toString()));
						Toast.makeText(ItemDetailActivity.this,"Values saved!",500).show();
						itemPriceText.setText("");
						//itemDescriptionText.setText("");
						buildList();
					}
				});
				incomeInputDialog.show();
			}
		});
        actionsButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				initializeActionsDialog();
			}
		});
    }
    
    public void initializeActionsDialog(){
    	final Dialog actionsDialog = new Dialog(ItemDetailActivity.this);
    	actionsDialog.setCancelable(true);
    	actionsDialog.setTitle("actions...");
    	actionsDialog.setContentView(R.layout.actionsdialog);
    	String[] actions = {"Edit","Delete"};
    	ListView actionList = (ListView)actionsDialog.findViewById(R.id.actionsList);
    	actionList.setAdapter(new ArrayAdapter<String>(ItemDetailActivity.this,android.R.layout.simple_list_item_1,actions));
    	actionList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				switch(arg2){
				case 0:	//Edit selected
						createEditDialog();
						actionsDialog.dismiss();
						break;
				case 1:	//Delete selected
						createDeleteConfirmDialog();
						actionsDialog.dismiss();
						break;	
				}
			}
		});
    	actionsDialog.show();
    }
    
    public void createEditDialog(){
    	final Dialog editDialog = new Dialog(ItemDetailActivity.this);
    	editDialog.setContentView(R.layout.addexpensedialog);
    	editDialog.setTitle("edit expense...");
    	final Button editButton = (Button)editDialog.findViewById(R.id.addButton);
    	final Button cancelButton = (Button)editDialog.findViewById(R.id.cancelButton);
    	final EditText itemDescriptionText = (EditText)editDialog.findViewById(R.id.itemDescriptionText);
    	final EditText itemPriceText = (EditText)editDialog.findViewById(R.id.itemPriceText);
    	editButton.setText(" Update ");
    	String rowIDString = rowIDText.getText().toString();
		final int rowID = Integer.parseInt(rowIDString);
		Cursor c = dbAdapter.getExpenseByRowID(rowID);
		startManagingCursor(c);
		c.moveToNext();
		if(c.isAfterLast()==false){
			itemDescriptionText.setText(c.getString(c.getColumnIndexOrThrow("description")));
			itemPriceText.setText(c.getString(c.getColumnIndexOrThrow("amount")));
		}
    	editButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				String description = itemDescriptionText.getText().toString();
				double amount = Double.parseDouble(itemPriceText.getText().toString());
				dbAdapter.updateExpense(rowID, description, amount);
				Toast.makeText(ItemDetailActivity.this,"Update Successful!",500);
				buildList();
				editDialog.dismiss();
				rowIDText.setText("");
			}
		});
    	cancelButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				editDialog.dismiss();
				rowIDText.setText("");
			}
		});
    	editDialog.show();
    }
    public void createDeleteConfirmDialog(){
    		final Dialog confirmDialog = new Dialog(ItemDetailActivity.this);
    		confirmDialog.setContentView(R.layout.confirmdialog);
    		confirmDialog.setTitle("Are you sure?");
    		String rowIDString = rowIDText.getText().toString();
    		final int rowID = Integer.parseInt(rowIDString);
    		Button yesButton = (Button)confirmDialog.findViewById(R.id.yesButton);
    		Button noButton = (Button)confirmDialog.findViewById(R.id.noButton);
    		noButton.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View arg0) {
					confirmDialog.dismiss();
					rowIDText.setText("");
				}
			});
    		yesButton.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View arg0) {
					dbAdapter.deleteExpense(rowID);
					Toast.makeText(ItemDetailActivity.this, "Delete Successful!", 500);
					confirmDialog.dismiss();
					rowIDText.setText("");
					buildList();
				}
			});
    		confirmDialog.show();
    }
    
    public void buildList(){
    	try{
            Cursor cursor = dbAdapter.fetchExpenseByItem(item);
            startManagingCursor(cursor);
    		cursor.moveToFirst();
    		ArrayList <HashMap<String,String>> mylist = new ArrayList<HashMap<String,String>>();
    		HashMap<String,String> map = new HashMap<String,String>();
    		DecimalFormat df = new DecimalFormat(currencySign+"##,##0.00");
    		System.out.println(cursor.getColumnCount());
    		double amt=0.00;
    		double sum=0.00;
    		String dateString="", monthString="", yearString="";
    		DecimalFormat doubleDigits = new DecimalFormat("00");
    		while(cursor.isAfterLast()==false){
    			map.put("ID",cursor.getString(0));
    			dateString=doubleDigits.format(cursor.getDouble(cursor.getColumnIndexOrThrow("dt")));
    			monthString = doubleDigits.format(cursor.getDouble(cursor.getColumnIndexOrThrow("month")));
    			yearString = doubleDigits.format(cursor.getDouble(cursor.getColumnIndexOrThrow("year")));
    			map.put("DT",dateString+"/"+monthString+"/"+yearString);
    			map.put("SOURCE", cursor.getString(4));
    			amt = cursor.getDouble(5);
    			sum+=amt;
    			map.put("AMOUNT", df.format(amt));
    			mylist.add(map);
    			System.out.println(map.toString());
    			map = new HashMap<String,String>();
    			cursor.moveToNext();
    		}
    		map.put("ID","");
    		map.put("DT","");
    		map.put("SOURCE", "TOTAL:");
    		map.put("AMOUNT",df.format(sum));
    		mylist.add(map);
    		Toast.makeText(getApplicationContext(),"Total Expense: "+sum,1000).show();
    		SimpleAdapter mIncomeMap;
    		mIncomeMap = new SimpleAdapter(ItemDetailActivity.this, mylist, R.layout.allincome_row, new String[]{"ID","DT","SOURCE","AMOUNT"}, new int[]{R.id.ID_CELL,R.id.DT_CELL,R.id.SOURCE_CELL,R.id.AMOUNT_CELL});
    		expenseList.setAdapter(mIncomeMap);
    		cursor.close();
            }catch(Exception ex){
            	ex.printStackTrace();
            }
    }
}